/*
 * CUCIPlug - program entry point
 * Kannan Ramanathan
 */
using System;
using System.Diagnostics;
using System.ComponentModel;
using PCAD.CAT;
using uciPlug.Properties;

namespace uciPlug
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class CUCIPlug
	{
        static CEngineProcess engineProcess;
        static System.IO.FileStream plugLog;
        static string engineName;
        static string logfilePath;
        static string defaultLogFile = "pluglog.txt";

        //static CEngine engine=null;
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
            try
            {
                setupPump();
                startPump();
            } 
            catch(Exception e)
            {
                string s = e.Message + "\n" + e.ToString();
                Console.WriteLine(s);
            }
        }

        private static void setupPump()
        {
            setupLogging();                               
            
            engineName = (!String.IsNullOrEmpty(Settings.Default.EngineName)) ? Settings.Default.EngineName : "toga.exe"; 
            
            engineProcess = new CEngineProcess(engineName); 
            CEngineProcess.DataRead += new DataReadHandler(CUCIPlug_DataRead);
            engineProcess.loadEngine();
            
            Trace.TraceInformation("PUMP: Engine {0} started @ {1}", engineName, DateTime.Now.ToLongTimeString());
            Trace.TraceInformation("PUMP: SETUP complete");
            Trace.WriteLine("--------------------------------------------------");

        }

        private static void setupLogging()
        {            
            try
            {
                logfilePath = Settings.Default.LogPath;
                if (String.IsNullOrEmpty(logfilePath))
                {
                    logfilePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                }
                // See if we can write to the uciPlug.exe folder itself...            
                plugLog = System.IO.File.Open(System.IO.Path.Combine(logfilePath, defaultLogFile), System.IO.FileMode.Append);

                // Setup the tracing pipe
                Trace.AutoFlush = true;
                Trace.Listeners.Add(new TextWriterTraceListener(plugLog));                         
            }
            catch (System.Exception e)
            {
                string s = e.Message + "\n" + e.ToString();
                Console.WriteLine(s);
            }
        }

        static void CUCIPlug_DataRead(int uniqueID, string data)
        {
            Console.WriteLine(data);
            Trace.WriteLine("RSP: "+data);
        }

        private static void startPump()
        {
            bool engineRunning = engineProcess.isEngineLoaded();
            string cmd = null;

            engineProcess.readEngineOutputLineAsynchronous();
            while (engineRunning)
            {
                cmd = Console.ReadLine();
                engineProcess.sendEngineCommandCRLF(cmd);
                Trace.WriteLine("-------|CMD: " + cmd);
                if (cmd.Equals("quit"))
                {
                    // get ready to quit
                    engineProcess.waitForExit();
                    engineRunning = false;
                    Trace.WriteLine("PUMP: Hit a quit in the stream. Quitting!");
                }
            }
        }


#region TEST_ENGINEPROCESS
        static void testCEngineProcess()
        {
            CEngineProcess p = new CEngineProcess("toga.exe");
            CEngineProcess p1 = new CEngineProcess("toga.exe");

            CEngineProcess.DataRead += new DataReadHandler(CEngineProcess_DataRead);

            p.loadEngine();
            p1.loadEngine();
            p.sendEngineCommandCRLF("uci");
            p1.sendEngineCommandCRLF("uci");

            p.readEngineOutputLineAsynchronous();
            p1.readEngineOutputLineAsynchronous();

            p1.sendEngineCommandCRLF("ucinew");
            p1.sendEngineCommandCRLF("position startpos");
            p1.sendEngineCommandCRLF("go infinite");
            //p1.readEngineOutputLineAsynchronous();            

            #region NOT_NEEDED
            System.Timers.Timer t = new System.Timers.Timer(10 * 1000);
            t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
            p.sendEngineCommandCRLF("Interval: " + t.Interval);

            p.sendEngineCommandCRLF(String.Format("Starttime: {0}:{1}:{2}:{3}",
                DateTime.Now.Hour,
                DateTime.Now.Minute,
                DateTime.Now.Second,
                DateTime.Now.Millisecond));

            t.Start();

            while (okToProceed != true)
            {
                ;
            }
            p.sendEngineCommandCRLF(eventTime);
            p.sendEngineCommandCRLF(String.Format("StopTime: {0}:{1}:{2}:{3}",
                DateTime.Now.Hour,
                DateTime.Now.Minute,
                DateTime.Now.Second,
                DateTime.Now.Millisecond));

            t.Stop();
            #endregion

            p.sendEngineCommandCRLF("quit");
            p1.sendEngineCommandCRLF("stop");
            p1.sendEngineCommandCRLF("quit");

            p.waitForExit();
            p1.waitForExit();            

        }
        static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            eventTime = String.Format("EventTime: {0}:{1}:{2}:{3}",
                e.SignalTime.Hour,
                e.SignalTime.Minute,
                e.SignalTime.Second,
                e.SignalTime.Millisecond);
            okToProceed = true;
        }

        static void CEngineProcess_DataRead(int id, string data)
        {
            Console.WriteLine("UCIPLUG::{0}::{1}", id, data);
        }
        static bool okToProceed = false;
        static string eventTime;

#endregion

    }
}
